import React, { useContext, useEffect, useState } from 'react';
import SettingContext from './index';

const getFilterValue = (value, filter) => {
  const arr = [];
  filter.forEach((i) => {
    arr.push(value[i]);
  });
  return arr;
};
/*
 * 封装一个类似connect 的高阶组件
 *
 *
 * */
const connect = (arr) => {
  return (Cmp) => {
    return React.memo((props) => {
      const settings = useContext(SettingContext);
      const getProps = () => {
        // 不判断重名情况，直接覆盖
        return {
          settings,
          ...props,
        };
      };
      const [propsFinal, setPropsFinal] = useState({ ...getProps() });

      // 监听setting数据变化
      useEffect(() => {
        setPropsFinal({ ...getProps() });
      }, getFilterValue(settings, arr));

      // 监听setting数据变化
      useEffect(() => {
        setPropsFinal({ ...getProps() });
      }, [props]);

      return <Cmp {...propsFinal} />;
    });
  };
};

export default connect;
